package com.specter.serv.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.specter.mvc.model.dao.BaseDao;
import com.specter.mvc.model.service.Restrictions;
import com.specter.serv.service.AreaService;

/**
 * 行政区划 服务实现类
 *
 * @author Liang.Wang
 * @since 2017-03-29
 */
@Service
public class AreaServiceImpl implements AreaService {
	private String prefix = "com.specter.serv.entity.Area";
	private @Autowired BaseDao baseDao;

	@Override
	public Object show(String areaCode) {
		Assert.notNull(areaCode, "areaCode不能为空！");
		Restrictions r = Restrictions.me().eq("areaCode", areaCode);
		return baseDao.selectOne(prefix + ".select_area_show", r.params());
	}

	@Override
	public String name(String areaCode) {
		Restrictions r = Restrictions.me().eq("areaCode", areaCode);
		// 直辖市
		if (StringUtils.startsWithAny(areaCode, "11", "12", "31", "50")) {
			r.eq("areaType", "pdtv");
		}
		// 自治区
		else if (StringUtils.startsWithAny(areaCode, "15", "45", "54", "64", "65")) {
			r.eq("areaType", "cdtv");
		}
		// 普通省
		else {
			r.eq("areaType", "pcdtv");
		}
		return baseDao.selectOne(prefix + ".select_area_name", r.params());
	}

	@Override
	public List<?> sons(String areaCode) {
		Restrictions r = Restrictions.me().llike("areaCode", areaCode);
		return baseDao.select(prefix + ".select_area_list", r.params());
	}

	@Override
	public List<?> next(String areaCode) {
		areaCode = areaCode == null || areaCode.length() < 2 ? "" : areaCode;
		Restrictions r = Restrictions.me();
		// 全国所有省
		if ("".equals(areaCode)) {
			r.eq("areaLeve", 2);
		}
		// 11,12,31,50 直辖市直接到区县
		else if ("11,12,31,50".contains(areaCode)) {
			r.llike("areaCode", areaCode).eq("areaLeve", 4);
		}
		// 正常级别
		else {
			r.llike("areaCode", areaCode).eq("areaLeve", Area.area(areaCode).next().leve());
		}
		return baseDao.select(prefix + ".select_area_list", r.params());
	}

}
